package com.solver.controller.user;

import com.solver.constant.StatusConstant;
import com.solver.entity.Question;
import com.solver.result.Result;
import com.solver.service.QuestionService;
import com.solver.vo.QuestionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")

    public Result<List<QuestionVO>> list(Long categoryId) {

        //构造redis中的key
        String key = "question_" + categoryId;

        //查询是否有内容 如果有直接返回，不需要查sql
        List<QuestionVO> questionsList = (List<QuestionVO>) redisTemplate.opsForValue().get(key);
        if(questionsList != null && questionsList.size() > 0){
            return Result.success(questionsList);
        }

        //redis无法查询出结果 则需要查询sql 需要将查询结果放入redis
        Question question = new Question();
        question.setCategoryId(categoryId);
        question.setStatus(StatusConstant.ENABLE);//查询起售中问题

        List<QuestionVO> list = questionService.listWithDifficulty(question);
        redisTemplate.opsForValue().set(key,list);

        return Result.success(list);
    }

}
